# -*- coding:Utf-8 -*-
'''
Created on 28 nov. 2012

@author: fefoley
'''


import datetime
import myalgo


class Mail(object):
    """
    un mail avec les données suivantes : 
    CreationTime    LastModificationTime    Sent    SentOn    Subject    Sender    To    CC    BCC    BodyFormat    BodyLen    Size    Attachments:Size
    """


    def __init__(self, csv_line):
        """
        Read a line from a csv file : 
        **** CSV headers ***
        CreationTime
        LastModificationTime
        Sent
        SentOn
        Subject
        Sender
        To
        CC 
        BCC 
        BodyFormat 
        BodyLen   
        Size  
        Attachments:Size
        setup
        setdown
        adherence 
        """
        linesplit = csv_line.rstrip('\n').rstrip('\r').split('\t')  # take off endofline and split with TAB  (!!! might be also linefeed !
        if len(linesplit) != 13:
            raise Exception("format error for {}".format(linesplit))  # should be 13 fields - could be some formatting errors
        strCreationTime, \
        strLastModificationTime, \
        strSent, \
        strSentOn, \
        strSubject, \
        strSender, \
        lstTo, \
        lstCC, \
        lstBCC, \
        strBodyFormat, \
        strBodyLen, \
        strSize, \
        strAttachements_Size = linesplit        

        self.CreationTime = datetime.datetime.strptime(strCreationTime, "%d/%m/%Y %H:%M:%S")
        self.LastModificationTime = datetime.datetime.strptime(strLastModificationTime, "%d/%m/%Y %H:%M:%S")
        self.isSent = strSent
        self.SentOn = datetime.datetime.strptime(strSentOn, "%d/%m/%Y %H:%M:%S")
        self.Subject = strSubject
        self.Sender = strSender
        self.To = lstTo.split(';')
        self.CC = lstCC.split(';')
        self.BCC = lstBCC.split(';')
        self.BodyFormat = strBodyFormat
        self.BodyLen = int(strBodyLen)    #number of caracters
        self.Size  = int(strSize)      #bytes
        self.Attachements_Size = []
        if strAttachements_Size != "":
            if strAttachements_Size[0] != ";":   #seems like sometimes I have a ";####" string
                atts = strAttachements_Size.split(';') #flat list
                atts = list(zip(atts[::2], atts[1::2]))  #group by2
                atts = myalgo.remove_unwanted_attachements(atts)
                self.Attachements_Size = atts  
 
        self.setup_minutes = 0
        self.setdown_minutes = 0
        self.adh_minutes = 0
                        
    def set_setup(self, up, down, adh):
        self.setup_minutes = up
        self.setdown_minutes = down
        self.adh_minutes = adh


    def getdatetime(self):
        """method to return the datetime.datetime when the mail was written"""
        return self.SentOn

    def __str__(self):
        return "{}\t{}\t{}\t{}\t{}\t{}".format(self.SentOn.strftime("%c"), \
                                               self.Subject, \
                                               self.To, \
                                               self.CC, \
                                               self.BCC, \
                                               str(self.Attachements_Size))

    def __repr__(self):
        return "{}\t{}\t{}\t{}\t{}\t{}".format(self.SentOn.strftime("%c"), \
                                               self.Subject, \
                                               self.To, \
                                               self.CC, \
                                               self.BCC, \
                                               str(self.Attachements_Size))


class Meeting(object):
    """un meeting avec des données"""

    def __init__(self, csv_line):
        """
        Read a line from a csv file : 
        **** CSV headers ***
        CreationTime
        Start
        End
        Duration
        BusyStatus
        MeetingStatus
        Subject
        Location
        Organizer
        RequiredAttendees
        OptionalAttendees
        Attachements;Size
        IsRecurring
        setup
        setdown
        adherence        
        *********************
        """
        linesplit = csv_line.rstrip('\n').split('\t')  # take off endofline
        if len(linesplit) != 13: 
            raise Exception("format error for {}".format(linesplit))  # should be 13 fields - could be some formatting errors
        
        CreationTime, \
        Start, \
        End, \
        Duration, \
        self.BusyStatus, \
        self.MeetingStatus, \
        self.Subject, \
        self.Location, \
        self.Organizer, \
        RequiredAttendees, \
        OptionalAttendees, \
        Attachements_Size, \
        self.IsRecurring = linesplit
        
        self.CreationTime = datetime.datetime.strptime(CreationTime, "%d/%m/%Y %H:%M:%S")
        
        'must check the kind of format of Start/End.'   ################## A REVOIR ##########    
        'can be "%d/%m/%Y %H:%M:%S" or "%d/%m/%Y" - otherwise, raise an EXception'
        if len(Start) == 10: 
            self.Start = datetime.datetime.strptime(Start, "%d/%m/%Y")  # it is the short format         
        elif len(Start) == 19: 
            self.Start = datetime.datetime.strptime(Start, "%d/%m/%Y %H:%M:%S") # it is the long format           
        else: 
            raise Exception("format error for {}".format(linesplit))   
        
        if len(End) == 10: 
            self.End = datetime.datetime.strptime(End, "%d/%m/%Y") - datetime.timedelta(seconds=1) # it is the short format
        elif  len(End) == 19: 
            self.End = datetime.datetime.strptime(End, "%d/%m/%Y %H:%M:%S")  # it is the long format
        else: 
            raise Exception("format error for {}".format(linesplit))
        
#        if (len(Start) == 10 and len(End) == 19) or (len(Start) == 19 and len(End) == 10):
#            print('WEIRD! start: '+Start + ' - end: '+End + ' - subject: ' + self.Subject)
             
        self.Duration = datetime.timedelta(minutes=int(Duration))
        self.RequiredAttendees = RequiredAttendees.split(';')
        self.OptionalAttendees = OptionalAttendees.split(';')
        self.Attachements_Size = []
        if Attachements_Size != "":
            if Attachements_Size[0] != ";":   #seems like sometimes I have a ";####" string
                atts = Attachements_Size.split(';') #flat list
                atts = list(zip(atts[::2], atts[1::2]))  #group by2
                atts = myalgo.remove_unwanted_attachements(atts)
                self.Attachements_Size = atts
        
        self.setup_minutes = 0
        self.setdown_minutes = 0
        self.adh_minutes = 0        

    def set_setup(self, up, down, adh):
        self.setup_minutes = up
        self.setdown_minutes = down
        self.adh_minutes = adh        
    
    def getsender(self):
        """method to return the organizer name"""
        return self.Organizer
    
    def getsentdatetime(self):
        """method to return the datetime.datetime when the meeting was sent"""
        return self.CreationTime
    
    def getdatetime(self):   ############ to check  ########
        """method to return the datetime.datetime when the meeting was held"""
        return self.Start

    def __str__(self):
        str2print = self.CreationTime.strftime("%d/%m/%Y %H:%M:%S")
        str2print = str2print + '\t' + self.Start.strftime("%d/%m/%Y %H:%M:%S")
        str2print = str2print + '\t' + self.End.strftime("%d/%m/%Y %H:%M:%S")
        str2print = str2print + '\t' + str(self.Duration)
        str2print = str2print + '\t' + self.BusyStatus
        str2print = str2print + '\t' + self.MeetingStatus
        str2print = str2print + '\t' + self.Subject
        str2print = str2print + '\t' + self.Location
        str2print = str2print + '\t' + self.Organizer
        str2print = str2print + '\t' + str(self.RequiredAttendees)
        str2print = str2print + '\t' + str(self.OptionalAttendees)
        str2print = str2print + '\t' + str(self.Attachements_Size)
        str2print = str2print + '\t' + self.IsRecurring    
        return str2print

    def __repr__(self):
        str2print = self.CreationTime.strftime("%d/%m/%Y %H:%M:%S")
        str2print = str2print + '\t' + self.Start.strftime("%d/%m/%Y %H:%M:%S")
        str2print = str2print + '\t' + self.End.strftime("%d/%m/%Y %H:%M:%S")
        str2print = str2print + '\t' + str(self.Duration)
        str2print = str2print + '\t' + self.BusyStatus
        str2print = str2print + '\t' + self.MeetingStatus
        str2print = str2print + '\t' + self.Subject
        str2print = str2print + '\t' + self.Location
        str2print = str2print + '\t' + self.Organizer
        str2print = str2print + '\t' + str(self.RequiredAttendees)
        str2print = str2print + '\t' + str(self.OptionalAttendees)
        str2print = str2print + '\t' + str(self.Attachements_Size)
        str2print = str2print + '\t' + self.IsRecurring   
        return str2print + '\n'

